package com.example.zuo_cheng_yun.chapter1_stack;

import java.util.Stack;

/**
 * 实现一个特殊的栈，在实现栈的基本功能基础上，再实现返回栈中最小元素的操作
 * <p>
 * 要求：
 * 1.pop,push,getMin操作时间复杂度为O(1)
 * 2.设计的栈类型可以使用现成的栈结构
 */
public class N01_Mystack {

    private Stack<Integer> dataStack;
    private Stack<Integer> minStack;

    public N01_Mystack() {
        dataStack = new Stack<>();
        minStack = new Stack<>();
    }

    public Integer pop() {
        if (dataStack.isEmpty()) {
            throw new RuntimeException("empty");
        }

        Integer pop = dataStack.pop();
        Integer min = minStack.peek();
//        if (pop <= min) {
        if (pop == min) {
            minStack.pop();
        }
        return pop;
    }

    public void push(Integer data) {
        dataStack.push(data);
        if (minStack.isEmpty()) {
            minStack.push(data);
        } else  {
            Integer min = minStack.peek();
            if (data <= min) {
                minStack.push(data);
            }
        }
    }

    public Integer getMin() {
        if (minStack.isEmpty()) {
            throw new RuntimeException("empty");
        }
        return minStack.peek();
    }

}
